package com.bxl.chooser.server;

import com.bxl.chooser.bean.ChooseResponseMsg;
import com.bxl.chooser.context.ChooserContext;
import com.bxl.netty.rpc.common.context.Context;
import com.bxl.netty.rpc.common.message.MsgResponseContent;
import com.bxl.netty.rpc.common.message.PackageMsg;
import com.bxl.netty.rpc.common.message.RpcHeader;
import com.bxl.netty.rpc.common.serialize.Serialize;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;


/**
 * <>
 *
 * @author baixl
 * @date 2021/2/23
 */
public class ChooseServerMsgEncoder extends MessageToByteEncoder<PackageMsg<ChooseResponseMsg>> {
    private Context context;
    private Serialize serialize;

    public ChooseServerMsgEncoder() {
    }

    public ChooseServerMsgEncoder(Context context) {
        assert context == null;
        this.context = context;
        this.serialize = context.getSerialize();
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, PackageMsg<ChooseResponseMsg> message, ByteBuf out) throws Exception {

        RpcHeader header = message.getHeader();
        out.writeInt(header.getFlag());
        out.writeLong(header.getRequestID());
        Object content = message.getContent();
        if (content == null) {
            out.writeInt(0);
        } else {
            byte[] contetnByte = this.serialize.serialize(content);
            out.writeInt(contetnByte.length);
            // 写入消息主体信息
            out.writeBytes(contetnByte);
        }

    }
}
